package com.ruoyi.web.controller.video;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.video.domain.dto.CameraDto;
import com.ruoyi.video.service.HlsService;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Hls控制器
 * @Author: orange
 * @CreateTime: 2025-01-16
 */
@RestController
public class HlsController {

    // 注入HlsService
    @Autowired
    private HlsService hlsService;


    @Anonymous
    @RequestMapping({"hls"})
    public void video(CameraDto cameraDto, HttpServletResponse response) throws IOException {
        // 判断cameraDto中的url是否为空
        if (StrUtil.isBlank(cameraDto.getUrl())) {
            // 设置响应内容类型为json
            response.setContentType("application/json");
            // 将"参数有误"写入响应输出流
            response.getOutputStream().write("参数有误".getBytes("utf-8"));
            // 刷新响应输出流
            response.getOutputStream().flush();
        } else {
            // 使用MD5算法对url进行加密
            String mediaKey = MD5.create().digestHex(cameraDto.getUrl());
            // 从缓存中获取hls
            byte[] hls = (byte[])HlsService.cacheM3u8.get(mediaKey);
            // 判断hls是否为空
            if (null == hls) {
                // 设置响应内容类型为json
                response.setContentType("application/json");
                // 将"尚未生成m3u8"写入响应输出流
                response.getOutputStream().write("尚未生成m3u8".getBytes("utf-8"));
                // 刷新响应输出流
                response.getOutputStream().flush();
            } else {
                // 设置响应内容类型为m3u8
                response.setContentType("application/vnd.apple.mpegurl");
                // 将hls写入响应输出流
                response.getOutputStream().write(hls);
                // 刷新响应输出流
                response.getOutputStream().flush();
            }
        }

    }
}
